/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.tutwiz;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.tutwiz.controller.FrontController;

/**
 *
 * @author danielwirdehall
 */
public class FileFilter implements Filter {
	
	
	List allowedFileEndings;
	
	// The filter configuration object we are associated with.  If
	// this value is null, this filter instance is not currently
	// configured. 
	private FilterConfig filterConfig = null;
	
	public FileFilter() {
		allowedFileEndings = new LinkedList();
		allowedFileEndings.add("xhtml");
		allowedFileEndings.add("jsp");
		allowedFileEndings.add("js");
		allowedFileEndings.add("png");
		allowedFileEndings.add("jpg");
		allowedFileEndings.add("gif");
		allowedFileEndings.add("css");
        allowedFileEndings.add("ico");
	}	


	/**
	 *
	 * @param request The servlet request we are processing
	 * @param response The servlet response we are creating
	 * @param chain The filter chain we are processing
	 *
	 * @exception IOException if an input/output error occurs
	 * @exception ServletException if a servlet error occurs
	 */
	// Ser till att alla request som inte är av följande typer: css, gif, jpg, png, js, jsp, xhtml
	// skickas genom vårt MVC strukturerade ramverk.
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain)
			throws IOException, ServletException {
		
		URL theUrl = new URL(((HttpServletRequest)request).getRequestURL().toString());
		
		int filePosition = theUrl.getPath().lastIndexOf(".");
		String fileEnding = "";
		if (filePosition != -1) {
			fileEnding = theUrl.getPath().substring(theUrl.getPath().lastIndexOf(".")+1);
		}
		if (allowedFileEndings.contains(fileEnding)) {
			System.out.println(fileEnding);
			chain.doFilter(request, response);
		} else {
			FrontController fc = new FrontController((HttpServletRequest)request, (HttpServletResponse)response);
		}
	}


	/**
	 * Destroy method for this filter 
	 */
	public void destroy() {		
	}

	/**
	 * Init method for this filter 
	 */
	public void init(FilterConfig filterConfig) {		
		this.filterConfig = filterConfig;
		if (filterConfig != null) {
			
		}
	}

	/**
	 * Return a String representation of this object.
	 */
	@Override
	public String toString() {
		if (filterConfig == null) {
			return ("FileFilter()");
		}
		StringBuffer sb = new StringBuffer("FileFilter(");
		sb.append(filterConfig);
		sb.append(")");
		return (sb.toString());
	}
}
